<?php
/**
 * 这个是购买的百度智能云词法分析接口，
 * 购买链接 https://ai.baidu.com/tech/nlp_basic/lexical
 */
namespace com;

class Lexer {

    protected static $apiKey = null;
    protected static $secretKey = null;
    
    //设置APPKey
    public static function setAppKey($apiKey, $secretKey){
        self::$apiKey = $apiKey;
        self::$secretKey  = $secretKey;
    }

    public static function run($bodys) {
        $curl = curl_init();
        $accessToken = self::getAccessToken();
        curl_setopt_array($curl, array(
            CURLOPT_URL => "https://aip.baidubce.com/rpc/2.0/nlp/v1/lexer?charset=UTF-8&access_token={$accessToken}",
            CURLOPT_TIMEOUT => 30,
            CURLOPT_RETURNTRANSFER => true,
            CURLOPT_SSL_VERIFYPEER  => false,
            CURLOPT_SSL_VERIFYHOST  => false,
            CURLOPT_CUSTOMREQUEST => 'POST',
            
            CURLOPT_POSTFIELDS => $bodys,//{"text":"我的头难受"}
    
            CURLOPT_HTTPHEADER => array(
                'Content-Type: application/json',
                'Accept: application/json'
            ),
        ));
        $response = curl_exec($curl);
        curl_close($curl);
        return $response;
    }
    
    /**
     * 使用 AK，SK 生成鉴权签名（Access Token）
     * @return string 鉴权签名信息（Access Token）
     */
    private static function getAccessToken(){
        $curl = curl_init();
        $postData = array(
            'grant_type' => 'client_credentials',
            'client_id' => self::$apiKey,
            'client_secret' => self::$secretKey
        );
        curl_setopt_array($curl, array(
            CURLOPT_URL => 'https://aip.baidubce.com/oauth/2.0/token',
            CURLOPT_CUSTOMREQUEST => 'POST',
            CURLOPT_SSL_VERIFYPEER  => false,
            CURLOPT_SSL_VERIFYHOST  => false,
            CURLOPT_RETURNTRANSFER => true,
            CURLOPT_POSTFIELDS => http_build_query($postData)
        ));
        $response = curl_exec($curl);
        curl_close($curl);
        $rtn = json_decode($response);
        return $rtn->access_token;
    }
}